<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
      layout:decorator="base"
      th:with="pageTitle='上传文件'">
<head>
    <link rel="stylesheet" th:href="@{/css/index.css}">
    <!--<script th:src="@{/js/wangEditor.min.js}"></script>-->
    <style>

        .v-model {
            position: absolute;
            z-index: 99
        }

        .w-e-text-container {
            height: 400px !important;
        }

    </style>

</head>
<body>
<th:block layout:fragment="custom_content">
    <div id="loading"></div>

    <el-form id="uploadFileForm" enctype="multipart/form-data" method="post" action="/regulation/saveword"  >
        <!--标题：-->
        <!--<el-input value="" name="title" v-model="title" id="title" width="100px"></el-input>-->

        <!--<el-form-item label="标题：" prop="title">-->
            <!--<el-input v-model="title" id="title" size="mini" class="input"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="请选择目录：">
            <span>{{ catalog}}</span>
            <el-button type="primary" size="mini" @click="handleAdd">选择目录</el-button>
        </el-form-item>
        <el-dialog
                title="选择目录"
                :visible.sync="selDialogVisible"
                size="tiny"
                :before-close="handleAddClose" id="selDialogVisible">
            <el-tree
                    :data="regulations"
                    show-checkbox
                    :check-strictly="true"
                    @check-change="handleClick"
                    node-key="id"
                    ref="tree"
                    :default-checked-keys="defaultCheckedKeys"
                    default-expand-all
                    :expand-on-click-node="false">
          <span class="custom-tree-node" slot-scope="scope">
            <span>{{  scope.node.label }}</span>
          </span>
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="selDialogVisible = false">取 消</el-button>
                <el-button size="mini" type="primary" @click="handleEditSave('editForm')">选择</el-button>
            </div>
        </el-dialog>

        <!-- 上传word -->
        <el-form-item label="上传文件：">
            <input id="excelFile" type="file" name="excelFile" style="display:none"
                   onchange="excelFileChange(this.files)"/>
            <el-button type="primary" @click="selectExcelFile" size="mini">选择文件</el-button>
            <span id="excelFileName">{{excelFileName}}</span>
            <el-button type="primary" @click="submitUpload" size="mini">文件上传<i
                    class="el-icon-upload el-icon--right"></i></el-button>
        </el-form-item>

        <br>
        <!--<el-button size="mini" type="primary" @click="saveword">保存</el-button>-->
    </el-form>

</th:block>
<th:block layout:fragment="javascript">
    <script>
        var isExist = false;
        var indexVue = new Vue({
            el: '#app',
            data: function () {
                return {
                    siderWidthDialog:false,
                    siderbarWidth:15,
                    fileList: [],
                    regulations: [],
                    defaultCheckedKeys: [],
                    excelFileName: '',
                    breadcrumbs:['上传文件'],

                    selDialogVisible: false,
                    title: '',
                    catalog: '',
                    catalogId: '',
                    content: '',
                    uploadFileForm: {
                        fileList: []
                    },
                    isCollapse: false,
                    defaultIndex: '1',
                    menus: [],
                    regulationMenus: [],
                    extraFiles: [],
                    deptTrees:[]
                }
            },
            methods: {
                handleRemove: function (file,fileList) {
                    indexVue.uploadFileForm.fileList = fileList;
                },
                handlePreview: function (file) {
                    indexVue.uploadFileForm.fileList = fileList;
                },
                handleExceed: function (files, fileList) {
                    indexVue.uploadFileForm.fileList = fileList;
                },
                beforeRemove: function (files, fileList) {
                    return this.$confirm('确定移除 ${ file.name }？');
                },
                handleAddClose: function () {
                    indexVue.selDialogVisible = false;
                },
                handleChange: function (file, fileList) {
                    this.fileList.push(fileList[0]);
                },
                handleClick: function (data, checked, node) {
                    if (checked == true) {
                        this.checkedId = data.id;
                        this.$refs.tree.setCheckedNodes([data]);
                    }
                },
                beforeAvatarUpload: function (file) {
                    var Doc = file.name.split('.');
                    if (Doc[1] === 'doc' || Doc[1] === 'docx') {
                        return false;
                    } else {
                        this.$message.error('上传文件只能是 doc/docx 格式!');
                        return false;
                    }
                },
                submitForm: function (formName) {
                    var $this = this;
                    indexVue.$refs['ruleForm'].validate(function (valid) {
                        if (valid) {
                            if (isExist) {
                                $this.$message.error('文件已存在，请勿重复上传!');
                                return false;
                            }
                            if ($this.fileList.length > 1) {
                                $this.$message.error('只能上传一个文件!');
                                return false;
                            }

                            $('#ruleForm').submit();
                        } else {
                            return false;
                        }
                    });
                },
                handleEditSave: function (formName) {
                    var nodes = this.$refs.tree.getCheckedKeys();
                    var url = "";
                    var catalogId = "";
                    for (var i = 0; i < nodes.length; i++) {
                        var list = new Object();

                        var id = nodes[i];
                        var node = this.$refs.tree.getNode(id);
                        //node.data获得数据
                        url = node.data.url;
                        catalogId = node.data.id;
                    }

                    this.catalog = url;
                    this.catalogId = catalogId;
                    indexVue.selDialogVisible = false;

                },
                selectExcelFile: function () {
                    $('#excelFile').click();
                },
                selectExcelFileExtra: function () {
                    $('#excelFileExtra').click();
                },
                handleAdd: function () {
                    indexVue.selDialogVisible = true;
                },
                delFile: function (index, fileId) {
                    this.extraFiles.splice(index, 1);
                },
                saveword: function () {
                    var $this = this;
                    if (this.catalogId == "") {
                        $this.$message({
                            showClose: true,
                            message: '请选择上传的目录',
                            type: 'error'
                        });
                        return;
                    }

                    if ($('#excelFileName').val() == undefined) {
                        $this.$message({
                            showClose: true,
                            message: '请上传文件',
                            type: 'error'
                        });
                        return;
                    }

                    if ($('#title').val() == '') {
                        $this.$message({
                            showClose: true,
                            message: '请输入标题',
                            type: 'error'
                        });
                        return;
                    }

                    var formData = new FormData();

                    formData.append('title', $('#title').val());
                    formData.append('catalogId', this.catalogId);

                    // var str = "_Toc";
                    // var regExp = new RegExp(searchText, 'g');//创建正则表达式，g表示全局的，如果不用g，则查找到第一个就不会继续向下查找了；
                    // var newHtml = html.replace(regExp, '<a class="highlight" >' + searchText + '</a>');//将找到的关键字替换，加上highlight属性；
                    // editor.txt.html(newHtml);
                    // getWord();

                    formData.append('content', getValue());

                },
                submitUpload: function () {
                    var $this = this;
                    if (this.catalogId == "") {
                        $this.$message({
                            showClose: true,
                            message: '请选择上传的目录',
                            type: 'error'
                        });
                        return;
                    }

                    if ($('#excelFileName').val() == undefined || $('#excelFileName').val()=="") {
                        $this.$message({
                            showClose: true,
                            message: '请选择文件后上传',
                            type: 'error'
                        });
                        return;
                    }

                    var formData = new FormData();
                    formData.append('excelFile', $('#excelFile')[0].files[0]);
                    formData.append('title', "");
                    formData.append('catalogId', $this.catalogId);

                    var loading = this.$loading({
                        lock: true,
                        text: '上传中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    $.ajax({
                        url: 'save',
                        type: 'POST',
                        cache: false,
                        data: formData,
                        processData: false,
                        contentType: false
                    })
                        .done(function (data) {
                        loading.close();

                        if (data.status == 1) {
                            $this.$alert('上传成功！', '提示', {
                                confirmButtonText: '确定',
                                callback : function callback() {
                                    location.href = "/regulation/search/";
                                }
                            });
                        } else {
                            $this.$message.error(data.msg);
                        }

                    }).fail(function (res) {
                        loading.close();
                        $this.$message({
                            showClose: true,
                            message: '上传失败',
                            type: 'error'
                        });
                    });
                },
                initMenu: function () {
                    var $this = this;
                    var data = commonInitMenu($this);
                    // setTimeout(function(){
                    //     $this.$nextTick(function () {
                    //         let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
                    //         let element = document.querySelector('.siderbar');
                    //         $(".logo-wrapper").css("width",element.clientWidth);
                    //     });
                    // },1000);
                },
                toggleMenu: function () {
                    this.isCollapse = !this.isCollapse;
                    window.localStorage.setItem('isCollapse',this.isCollapse);
                },
                changeSiderWidth:function(value){
                    changeSiderWidth(this,value);
                },
                openChangeSiderWidth:function(){
                    this.siderWidthDialog=true;
                }
            },
            created: function () {
                initCssProperty(this);
            }
        });

        // var E = window.wangEditor;
        // var editor = new E('#editor');
        $(function () {
            indexVue.initMenu();
            // editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
            //
            // editor.create();

            $.ajax({
                cache: false,
                url: '/regulation/data?newDate='+Math.random(),
                type: 'GET',
                data: {},
                dataType: 'json',
                contentType: 'application/json',
                async: false,
                success: function (data) {
                    if (data.status == 1) {

                        indexVue.regulations = data.value.regulations;
                    }
                }
            });
            changeFooterHeight();

        });
        function clearWord(){
            $('.highlight').each(function ()//找到所有highlight属性的元素；
            {
                $(this).parent().replaceWith("");//将他们的属性去掉；
            });
        }
        function setValue(content) {

            editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
            editor.create();
            editor.txt.html(content);
        }

        function getValue() {
            var b = new Base64();
            return b.encode(editor.txt.html());
        }

        function excelFileChange(files) {
            if (files) {
                var Doc = getCaption(files[0].name);

                if (Doc === 'doc' || Doc === 'docx') {
                    indexVue.excelFileName = files[0].name;
                    $("#excelFileName").val(files[0].name);
                    // this.$refs.input1.value = files[0].name;
                    return false;
                } else {
                    indexVue.$alert('上传文件只能是 doc/docx 格式!请重新选择！', '提示', {
                        confirmButtonText: '确定',
                        callback : function callback() {
                        }
                    });

                    return false;
                }
            }
        }

        function excelFileExtraChange(files) {
            var formData = new FormData();
            if($('#excelFileExtra')[0].files[0]==undefined){
                return;
            }
            formData.append('excelFileExtra', $('#excelFileExtra')[0].files[0]);
            $.ajax({
                url: '/regulation/savefile',
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                var item = {
                    fileId: res.value.fileId,
                    fileName: res.value.fileName,
                    fileUrl: res.value.fileUrl
                };

                indexVue.extraFiles.unshift(item);
            }).fail(function (res) {
                indexVue.$alert('上传附件失败！', '提示', {
                    confirmButtonText: '确定',
                    callback : function callback() {

                    }
                });
            });

        }
        function getCaption(obj) {
            var index = obj.lastIndexOf("\.");
            obj = obj.substring(index + 1, obj.length);
            return obj;
        }
        function valida(html,keyword) {
            if(html.indexOf(keyword)!=-1){

                return true;
            } else {

                return false;
            }
        }

        function Base64() {
            // private property
            _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

            // public method for encoding
            this.encode = function (input) {
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = _utf8_encode(input);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                        _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                        _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
                }
                return output;
            }

            // public method for decoding
            this.decode = function (input) {
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = _keyStr.indexOf(input.charAt(i++));
                    enc2 = _keyStr.indexOf(input.charAt(i++));
                    enc3 = _keyStr.indexOf(input.charAt(i++));
                    enc4 = _keyStr.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = _utf8_decode(output);
                return output;
            }

            // private method for UTF-8 encoding
            _utf8_encode = function (string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }

                }
                return utftext;
            }

            // private method for UTF-8 decoding
            _utf8_decode = function (utftext) {
                var string = "";
                var i = 0;
                var c = c1 = c2 = 0;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    } else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    } else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }

    </script>
</th:block>
</body>
</html>